package ;

import flash.display.Sprite;
/**
 * ...
 * @author test
 */
@:generic
class ObjectPool<T:(Sprite,{function new():Void;})> {
	//Array containing the objects.
	private var objects:Array<T>;

	//Current index for object recycling.
	private var current:Int;

	//Constructor... nothing else to say here.
	public function new(size:Int) {
		this.objects = new Array<T>();
		this.current = 0;
		for (i in 0...size) {
			this.objects.push(new T());
		}
	}

	//Getters and setters - BEGIN
	
	//------------------------------------------CHANGE TO PRIVATE
	
	public function getObjects():Array<T> {
		return this.objects;
	}

	private function getCurrent():Int {
		return this.current;
	}

	private function setCurrent(current:Int):Void {
		this.current = current;
	}
	//Getters and setters - END

	//Method to obtain an available object. If no object is available, returns null.
	public function getAvailableObject():T {
		var index:Int = this.getCurrent();
		var object:T = null;

		do {
			if (this.getObjects()[index].visible == false) {
				object = this.getObjects()[index];
			}
			index++;
			if (index == this.getObjects().length) {
				index = 0;
			}			
		} while ( (index != this.getCurrent()) && (object == null) );

		this.setCurrent(index);

		return object;
	}
}